<?php

class HomeController extends BaseController {

	/*
	|--------------------------------------------------------------------------
	| Default Home Controller
	|--------------------------------------------------------------------------
	|
	| You may wish to use controllers instead of, or in addition to, Closure
	| based routes. That's great! Here is an example controller method to
	| get you started. To route to this controller, just add the route:
	|
	|	Route::get('/', 'HomeController@showWelcome');
	|
	*/

	public $data = array();

	public function __construct(){
		session_start();
		$this->data['user_agent'] = $this->getUserAgent();
	}

	public function home_page() {
		if( Input::has('code') ){
            $code = Input::get('code');
            $arr = array(
                    'client_id' => Config::get('lib.client_id') ,
                    'client_secret' => Config::get('lib.client_secret') ,
                    'code' => $code , 'grant_type' => 'authorization_code'
                );
            $access = $this->curl_post( Config::get('lib.oauth_uri').'/token' , $arr );
            $access_result = json_decode($access , true);
            if( !$access_result['error'] ){
                $user_id        = $access_result['result']['user_id'];
                $token_type     = $access_result['result']['token_type'];
                $access_token   = $access_result['result']['access_token'];

                $_SESSION['user_id']        = $user_id;
                $_SESSION['authorization']  = $token_type.' '.$access_token;

                $info = $this->curl_get( Config::get('lib.ptime_api')."/user/".$user_id , "" , "user" , $token_type.' '.$access_token );
                $info_result = json_decode($info , true);
                if( !$info_result['error'] ){
                    $_SESSION['number'] = $info_result['result']['school_id'];
                    $_SESSION['token']  = $info_result['result']['token'];
                    $_SESSION['name']   = $info_result['result']['name'];
                    $_SESSION['icon']   = $info_result['result']['icon'];

					$check_user = DB::table('user')->select('id')->where('id','=',$user_id)->get();
					//本系统新用户，添加
					if( count($check_user) == 0 ){
						$insert_arr = array(
							'id' => $user_id ,
							'name' => $info_result['result']['name'] ,
							'number' => $info_result['result']['school_id']
							);
						$insert_id = DB::table('user')->insertGetId($insert_arr);
						if( $insert_id < 1 ){
							$this->data['check_false'] = 1;
						}
					}

					if( Input::has('state') ){
                        $redirectUrl = Input::get('state');
                        return Redirect::to($redirectUrl);
                    }

                }else{
					echo 'error code 2';
					var_dump($info_result);exit;
				}
            }else{
				echo 'error code 1';
				var_dump($access_result);exit;
			}
        }

        if( empty($_SESSION['user_id']) ){
			$state          = urlencode( Config::get("lib.app_url") );
            $redirectUrl    = Config::get("lib.oauth_uri")."/auth?client_id=".Config::get("lib.client_id")."&response_type=code&state=$state";
            return Redirect::to($redirectUrl);
        }else{
			$this->data['user_id'] 	= $_SESSION['user_id'];
			$this->data['icon'] 	= $_SESSION['icon'];
		}


		$this->data['hot_search'] = array( "word" , "ppt" , "林海雪原" , "abaqus" , "小区规划" , " 基业长青" , "白夜行" , "设计心理学");

		$hot_books = array();
		$hot_books[] = array(
			'href' => 'item.php?marc_no=0000285625' ,
			'image' => 'http://img3.doubanio.com/mpic/s2616137.jpg' ,
			'name' => "运筹学:应用范例与解法" ,
			'brief' => "本书内容包括建模理论概述,线性代数基础知识,线性规则,单纯形算法和目标规划,灵敏度分析:应用方法,灵敏度分析和对偶理论,运输、指派和转运问题,网络模型,整数规划,线性规划的高级主题,非线性规划,对策论.附录:@Risk锦囊、案例。" ,
			'author' => '温斯顿 (Winston, Wayne L.) 著' ,
			'press' => '北京:清华大学出版社,2006'
			);
		$hot_books[] = array(
			'href' => "item.php?marc_no=0000480207" ,
			'image' => 'http://img3.douban.com/mpic/s28118983.jpg' ,
			'name' => "太阳简史:一颗恒星的传记" ,
			'brief' => "银河系大约有3000 亿颗恒星，太阳是其中很普通的一颗，然而，这颗距离我们最近的恒星却是宇宙中唯一一颗对我们至关重要的恒星——数千年前人们就已经认识到了太阳的重要性，自古以来人们一直在尝试去理解太阳及其在宇宙中的地位，但直到最近，我们才开始真正认识太阳。 这是一本带你全面了解太阳的指南。它将告诉你太阳是如何诞生的，内部构造是什么样子，巨大的能量是如何维持的，又是如何影响我们的历史和生活的，以及太阳最终将如何毁灭地球。书中精美绝伦的太阳图片均由美国国家航空航天局提供，突出展示了“太阳动力学天文台”卫星拍摄到的壮美图片。" ,
			'author' => '库珀 (Cooper, Christopher) 著' ,
			'press' => '北京:人民邮电出版社,2015'
			);
		$hot_books[] = array(
			'href' => "item.php?marc_no=0000376766" ,
			'image' => 'http://img3.doubanio.com/mpic/s24399516.jpg' ,
			'name' => "铝合金材料组织与金相图谱" ,
			'brief' => "本书详细介绍了铝及铝合金8个系以及粉末冶金铝合金双金属复合板的主要相组成及其特征等。" ,
			'author' => '李学朝 编著' ,
			'press' => '北京:冶金工业出版社,2010'
			);

		$this->data['hot_books'] = $hot_books;

		header("Content-type: text/html; charset=utf-8");

		return View::make("index" , $this->data);
	}


	public function goToPtimeLogin(){
		$auth_url = Config::get('lib.auth_uri');

		$return_uri_ori = Config::get('lib.return_uri');
		if( Input::has('return_url') ){
			$return_uri_ori = Input::get('return_url');
		}
		$client_id = "-JCtVGLFXyZ0MXbNJ_h931WFk92QyDLD";
		$response_type = "token";
		$random_str = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYAZabcdefghijklmnopqrstuvwxyz";	//共62位
		$state = "";
		for( $i=0 ; $i<10 ; $i++ ){
			$random_index = mt_rand(0 , 51);
			$temp_str = substr( $random_str , $random_index , 1 );
			$state .= $temp_str;
		}

		$target_url = $auth_url."?client_id=".Config::get('lib.client_id')."&response_type=".$response_type."&redirect_uri=".$return_uri_ori."&state=".$state;

		return Redirect::to($target_url);
	}


	public function getUserAgent(){
        if( strpos($_SERVER['HTTP_USER_AGENT'], 'PTime.IOSWeb') !== false):
            $userAgent = "ptimeios";
        elseif( strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false):
            $userAgent = "wechat";
        elseif( strpos($_SERVER['HTTP_USER_AGENT'], 'PTime.AndroidWeb') !== false):
            $userAgent = "ptimeandroid";
        elseif( strpos($_SERVER['HTTP_USER_AGENT'], 'MQQBrowser')!== false):
            $userAgent = "mqq";
        else:
            $userAgent = "other";
        endif;
        return $userAgent;
    }


	function goToPtimeCampus(){
		$user_id = $_SESSION['user_id'];
		$auth_uri = Config::get('lib.campus_uri')."/auth?state=".urlencode(Config::get('lib.back_uri'))."&user_id=".$user_id."&system_cat=library";
		return Redirect::to($auth_uri);
	}

	function goToPtimeCampusBack(){
		echo 1;exit;
	}

}
